package com.xcm.controller;

import com.xcm.constant.BaseConstant;
import com.xcm.constant.SysAuthorityConstants;
import com.xcm.exception.ServiceException;
import com.xcm.model.SysAuthority;
import com.xcm.model.response.JsonResponseBuilder;
import com.xcm.model.vo.SysAuthorityTreeVo;
import com.xcm.page.PageInfo;
import com.xcm.service.SysAuthorityService;
import com.xcm.validator.SysAuthorityValidator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限
 *
 * @author linqiang
 * @date 2018-04-13 9:15
 */
@Controller
@RequestMapping("/sysAuthority")
public class SysAuthorityController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SysAuthorityController.class);
    @Autowired
    private SysAuthorityService sysAuthorityService;

    /**
     * 新增权限
     *
     * @param sysAuthority 新增的权限
     * @return
     */
    @RequestMapping("/saveSysAuthority")
    @ResponseBody
    public Object saveSysAuthority(SysAuthority sysAuthority) {
        try {
            //表单必要属性验证
            String formValidateResult = SysAuthorityValidator.validateSysAuthority(sysAuthority);
            if (StringUtils.isNotBlank(formValidateResult)) {
                return JsonResponseBuilder.buildFail(formValidateResult);
            }
            String checkResultMsg = sysAuthorityService.canSave(sysAuthority);
            if (StringUtils.isNotBlank(checkResultMsg)) {
                return JsonResponseBuilder.buildFail(checkResultMsg);
            }
            sysAuthority = sysAuthorityService.saveAndGetId(sysAuthority);
            if (null != sysAuthority && null != sysAuthority.getAuthorityId()) {
                return JsonResponseBuilder.buildSuccess(sysAuthority);
            }
        } catch (Exception e) {
            logger.error("SysAuthorityController saveSysAuthority 新增权限失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysAuthorityConstants.SAVE_FAIL);
    }


    /**
     * 修改权限
     *
     * @param sysAuthority 修改的权限
     * @return
     */
    @RequestMapping("/updateSysAuthority")
    @ResponseBody
    public Object updateSysAuthority(SysAuthority sysAuthority) {
        try {
            //表单必要属性验证
            String formValidateResult = SysAuthorityValidator.validateSysAuthority(sysAuthority);
            if (StringUtils.isNotBlank(formValidateResult)) {
                return JsonResponseBuilder.buildFail(formValidateResult);
            }
            int effectRow = sysAuthorityService.update(sysAuthority);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysAuthorityConstants.UPDATE_SUCCESS);
            }
        } catch (ServiceException e) {
            logger.error("SysAuthorityController updateSysAuthority 更新权限失败：" + e.getMessage());
            return JsonResponseBuilder.buildFail(e.getMessage());
        } catch (Exception e) {
            logger.error("SysAuthorityController updateSysAuthority 更新权限失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysAuthorityConstants.UPDATE_FAIL);
    }


    /**
     * 删除权限
     *
     * @param authorityId 删除的权限id
     * @return
     */
    @RequestMapping("/deleteSysAuthority")
    @ResponseBody
    public Object deleteSysAuthority(Integer authorityId) {
        try {
            if (null == authorityId) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            int effectRow = sysAuthorityService.deleteById(authorityId);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysAuthorityConstants.DELETE_SUCCESS);
            }
        } catch (ServiceException e) {
            logger.error("SysAuthorityController deleteSysAuthority 删除权限失败：" + e.getMessage());
            return JsonResponseBuilder.buildFail(e.getMessage());
        } catch (Exception e) {
            logger.error("SysAuthorityController deleteSysAuthority 删除权限失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysAuthorityConstants.DELETE_FAIL);
    }

    /**
     * 批量删除权限
     *
     * @param authorityIdArr 批量删除的权限id(多个以英文逗号隔开)
     * @return
     */
    @RequestMapping("/batchDeleteSysAuthority")
    @ResponseBody
    public Object batchDeleteSysAuthority(String authorityIdArr) {
        try {
            if (null == authorityIdArr || StringUtils.isBlank(authorityIdArr)) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            int effectRow = sysAuthorityService.batchDelete(authorityIdArr);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysAuthorityConstants.DELETE_SUCCESS);
            }
        } catch (ServiceException e) {
            logger.error("SysAuthorityController batchDeleteSysAuthority 批量删除权限失败：" + e.getMessage());
            return JsonResponseBuilder.buildFail(e.getMessage());
        } catch (Exception e) {
            logger.error("SysAuthorityController batchDeleteSysAuthority 批量删除权限失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysAuthorityConstants.DELETE_FAIL);
    }

    /**
     * 查询权限列表
     *
     * @param roleId 角色id
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(Integer roleId, Integer userId) {
        try {
            List<SysAuthorityTreeVo> sysAuthorityListTreeByRole = sysAuthorityService.listTree(roleId);
            if (CollectionUtils.isEmpty(sysAuthorityListTreeByRole)) {
                sysAuthorityListTreeByRole = new ArrayList<>();
            }
            return JsonResponseBuilder.buildSuccess(sysAuthorityListTreeByRole);
        } catch (Exception e) {
            logger.error("SysAuthorityController list 查询权限列表失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }

    /**
     * 查询权限列表分页
     *
     * @param roleId   角色id
     * @param userId   用户id
     * @param pageNum  第几页
     * @param pageSize 每页几条
     * @return
     */
    @RequestMapping("/listPage")
    @ResponseBody
    public Object listPage(Integer roleId, Integer userId, Integer pageNum, Integer pageSize) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            if (null != roleId && roleId > 0) {
                paramMap.put("roleId", String.valueOf(roleId));
            }
            if (null != userId && userId > 0) {
                paramMap.put("userId", String.valueOf(userId));
            }
            PageInfo sysAuthorityPageInfo = sysAuthorityService.listPage(paramMap,
                    pageNum == null ? super.pageNum : pageNum,
                    pageSize == null ? super.pageSize : pageSize);
            return JsonResponseBuilder.buildSuccess(sysAuthorityPageInfo);
        } catch (Exception e) {
            logger.error("SysAuthorityController listPage 查询权限列表分页失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }

    /**
     * 根据id查询权限
     *
     * @param authorityId 权限主键
     * @return
     */
    @RequestMapping(value = "/getById")
    @ResponseBody
    public Object getById(Integer authorityId) {
        if (null == authorityId) {
            return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
        }
        try {
            SysAuthority sysDepartment = sysAuthorityService.getById(authorityId);
            if (null != sysDepartment) {
                return JsonResponseBuilder.buildSuccess(sysDepartment);
            }
        } catch (Exception e) {
            logger.error("SysAuthorityController getById 根据id查询权限失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }
}
